package com.uchedao.vehicledetection.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.adapter.IdeasExpandableListAdapter;
import com.uchedao.vehicledetection.adapter.PagerViewAdapter;
import com.uchedao.vehicledetection.config.Api;
import com.uchedao.vehicledetection.config.AppInfoManager;
import com.uchedao.vehicledetection.config.UserInfoManager;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.inf.IOnResultBack;
import com.uchedao.vehicledetection.inf.ISave;
import com.uchedao.vehicledetection.inf.IitemChickBack;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.PaintThickness;
import com.uchedao.vehicledetection.model.ResultBoolean;
import com.uchedao.vehicledetection.model.ResultInt;
import com.uchedao.vehicledetection.model.Skeleton;
import com.uchedao.vehicledetection.network.HttpRequest;
import com.uchedao.vehicledetection.network.SubmitRequest;
import com.uchedao.vehicledetection.service.UpCarPhotoService;
import com.uchedao.vehicledetection.utils.ActionBarFactory;
import com.uchedao.vehicledetection.utils.FileUpload;
import com.uchedao.vehicledetection.utils.KeyboardUtil;
import com.uchedao.vehicledetection.utils.ProgressDialogUtil;
import com.uchedao.vehicledetection.utils.T;
import com.uchedao.vehicledetection.utils.ToastUtil;
import com.uchedao.vehicledetection.utils.UploadPicUtil;
import com.uchedao.vehicledetection.view.FireView;
import com.uchedao.vehicledetection.view.TestView;
import com.uchedao.vehicledetection.view.UpLoadCarPicture;
import com.uchedao.vehicledetection.view.WaterDipView;
import com.uchedao.vehicledetection.view.accident.AccidentCoverView;
import com.uchedao.vehicledetection.view.accident.AccidentReinforcementView;
import com.uchedao.vehicledetection.view.accident.AccidentSkeletonView;
import com.uchedao.vehicledetection.view.baseinfo.BaseInfoCarInfoView;
import com.uchedao.vehicledetection.view.baseinfo.BaseInfoFormalityView;
import com.uchedao.vehicledetection.view.condition.ConditionAdviceView;
import com.uchedao.vehicledetection.view.condition.ConditionEngineView;
import com.uchedao.vehicledetection.view.condition.ConditionGuiseView;
import com.uchedao.vehicledetection.view.condition.ConditionInteriorView;
import com.uchedao.vehicledetection.view.condition.ConditionOutFunctionView;
import com.uchedao.vehicledetection.view.condition.ConditionPaintSurfaceView;
import com.uchedao.vehicledetection.view.condition.ConditionPaintThicknessView;
import com.uchedao.vehicledetection.view.condition.ConditionVFunctioniew;
import com.uchedao.vehicledetection.view.widget.ActionBarDrawerToggle;
import com.uchedao.vehicledetection.view.widget.CJDViewPage;
import com.uchedao.vehicledetection.view.widget.DrawerArrowDrawable;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickAction;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickActionList;
import com.uchedao.vehicledetection.view.widget.quickactionpopuwindow.QuickActionWidget;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends CJDBaseActivity {

    private String SUBMIT_ACCESS_TOKEN = "BE58D592F0Q85E23D3A6B4BBD20E3A0C";
    private String SUBMIT_URL = "http://120.26.143.191:8089/Submit";
    public static final String VINCARINFOR = "VinCarInfor";

    private QuickActionList mGrid;
    private DrawerLayout mDrawerLayout;
    private ExpandableListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerArrowDrawable drawerArrow;
    private boolean drawerArrowColor;
    private CJDViewPage mViewPage;
    //    private List<Class<?>> mViews;
    private List<View> mAdapterViews;
    private IdeasExpandableListAdapter mLeftLayoutAdapter;
    //    private ImageView fabIconNew;
//    private FloatingActionButton rightLowerButton;
//    private FloatingActionMenu rightLowerMenu;
    private View mTitleView;
    private int pageIndex = 0;
    private int groupIndex = 0;
    private View nowView;
    private PagerViewAdapter mAdapter;
    private ProgressDialog dialog;
    private FileUpload upload;

    private UploadPicUtil upUtil;
    private int reqCount;

    private boolean upPaintCover = false; // 漆膜厚度示意图是否上传成功
    private boolean upkeletonCover = false; // 事故勘察示意图是否上传成功
//    private VinCarInfor vinCarInfor;

    private MyReceiver mReceiver;
    private IntentFilter filter;

    @Override
    protected String getActivityTag() {
        return "MainActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        mViewPage = (CJDViewPage) findViewById(R.id.main_viewpage);
        mViewPage.setNoScroll(true);

//        initBottomMenu();

        mGrid = new QuickActionList(this);

        mTitleView = new ActionBarFactory().initActionbarForUnRight(this, "设置", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    mDrawerLayout.openDrawer(mDrawerList);
                }
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDrawerList.isShown()) {
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    mGrid.show(view);
                }
            }
        });

    }

    @SuppressLint("NewApi")
    @Override
    protected void initData() {
        isStart = false;

//        if (getIntent().hasExtra(VINCARINFOR)) {
//            vinCarInfor = (VinCarInfor) getIntent().getSerializableExtra(VINCARINFOR);
//        }

        ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(getResources().getDrawable(R.color.app_style_blue));
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);

        initQuickActionList();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ExpandableListView) findViewById(R.id.navdrawer);
        mDrawerList.setGroupIndicator(null);


        LinearLayout header = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_main_group_head_title, null, false);
        mDrawerList.addHeaderView(header);
        TextView carPlant = (TextView) header.findViewById(R.id.item_main_group_head_title_tv);
        carPlant.setText(GlobalInfo.draft.car_plate);

        drawerArrow = new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                drawerArrow, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
//                rightLowerButton.setVisibility(View.VISIBLE);
//                invalidateOptionsMenu();
                mAdapter.notifyDataSetChanged();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
//                rightLowerMenu.close(true);
//                rightLowerButton.setVisibility(View.GONE);
                KeyboardUtil.keyboardHide(MainActivity.this);
                mDrawerList.expandGroup(groupIndex);
//                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        //只展开一项
        mDrawerList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < mLeftLayoutAdapter.getGroupCount(); i++) {
                    if (groupPosition != i) {
                        mDrawerList.collapseGroup(i);
                    }
                }
            }
        });

        mDrawerToggle.syncState();


        mLeftLayoutAdapter = new IdeasExpandableListAdapter(this, new IitemChickBack() {
            @Override
            public void execute(int groupPosition, int ChildPosition, String title) {
                mDrawerLayout.closeDrawer(mDrawerList);

//                System.out.println("ws---groupPosition = " + groupPosition + "     ChildPosition=" + ChildPosition + "      title=" + title);

                //保存上一页的信息
                commonSave();

                setTitle(title);
                showPage(groupPosition, ChildPosition, title);
            }
        });

        mDrawerList.setAdapter(mLeftLayoutAdapter);

        mAdapterViews = new ArrayList<View>();
        mAdapterViews.add(new BaseInfoFormalityView(this));

        mAdapter = new PagerViewAdapter(mAdapterViews);

        mViewPage.setAdapter(mAdapter);

        showFirstPage("手续信息");

        mReceiver = new MyReceiver();
        filter = new IntentFilter();
        filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(MyReceiver.ACT_MAIN_RECEIVER);
    }

    private void initQuickActionList() {

        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.main_menu_save), getString(R.string.main_menu_save)));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.main_menu_next_ic), getString(R.string.main_menu_next)));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.main_menu_commit_ic), getString(R.string.main_menu_commit)));
        mGrid.addQuickAction(new QuickAction(getResources().getDrawable(R.mipmap.main_menu_save_to_draft_ic), getString(R.string.main_menu_save_back_draft)));
    }

    private void showFirstPage(String title) {
        setTitle(title);
        showPage(0, 0, title);
    }

    //下一页
    private void showNextPage() {
        if (pageIndex == 15) {
            return;
        }

        pageIndex = pageIndex + 1;

        int groupPosition = 0;
        int childPosition = 0;
        String title = "";

        if (pageIndex == 15) {
            groupPosition = 5;
            childPosition = 0;
        } else if (pageIndex == 14) {
            groupPosition = 4;
            childPosition = 0;
        } else if (pageIndex == 13) {
            groupPosition = 3;
            childPosition = 0;
        } else if (10 <= pageIndex && pageIndex <= 12) {
            groupPosition = 2;
            childPosition = pageIndex - 10;
        } else if (2 <= pageIndex && pageIndex <= 9) {
            groupPosition = 1;
            childPosition = pageIndex - 2;
        } else if (0 == pageIndex || 1 == pageIndex) {
            groupPosition = 0;
            childPosition = pageIndex;
        }

        title = mLeftLayoutAdapter.getItemList().get(groupPosition).get(childPosition);
        mLeftLayoutAdapter.setSelectedItem(title);
        for (int i = 0; i < 6; i++) {
            if (i == groupPosition) {
                mDrawerList.expandGroup(groupPosition);
            } else {
                mDrawerList.collapseGroup(groupPosition);
            }
        }
        setTitle(title);
        showPage(groupPosition, childPosition, title);

    }

    private void showPage(int groupPosition, int childPosition, String title) {

        switch (groupPosition) {
            case 0:
                pageIndex = childPosition;
                if (childPosition == 0) {
                    nowView = new BaseInfoFormalityView(this);
                } else {
                    nowView = new BaseInfoCarInfoView(this);
                }
                break;
            case 1:
                pageIndex = 2 + childPosition;
                nowView = getConditionView(childPosition);
                break;
            case 2:
                pageIndex = 10 + childPosition;
                nowView = getAccidentView(childPosition);
                break;
            case 3:
                pageIndex = 13 + childPosition;
                nowView = new WaterDipView(this);
                break;
            case 4:
                pageIndex = 14 + childPosition;
                nowView = new FireView(this);
                break;
            case 5:
                pageIndex = 15 + childPosition;
                nowView = new UpLoadCarPicture(this);
                break;
        }
        groupIndex = groupPosition;
        mAdapter.updataData(nowView);
        mViewPage.setCurrentItem(0);
    }

    private View getAccidentView(int index) {

        switch (index) {
            case 0:
                return new AccidentCoverView(this);
            case 1:
                return new AccidentReinforcementView(this);
            default:
                return new AccidentSkeletonView(this);
        }
    }

    private View getConditionView(int index) {

        switch (index) {
            case 0:
                return new ConditionPaintThicknessView(this);
            case 1:
                return new ConditionPaintSurfaceView(this);
            case 2:
                return new ConditionGuiseView(this);
            case 3:
                return new ConditionInteriorView(this);
            case 4:
//                ConditionVFunctioniew view = new ConditionVFunctioniew(this, vinCarInfor);
//                view.setCarInfoFromVin();
//                return view;
                return new ConditionVFunctioniew(this);
            case 5:
                return new ConditionOutFunctionView(this);
            case 6:
                return new ConditionEngineView(this);
            case 7:
                return new ConditionAdviceView(this);
            default:
                return new TestView(this);
        }
    }

    @Override
    protected void initListener() {
        mGrid.setOnQuickActionClickListener(mActionListener);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ((IOnResultBack) nowView).onActivityResultView(requestCode, resultCode, data);
//
//        if (requestCode == UpLoadCarPicture.FROM_CAMERA_UP_LOADCARPACTURE || requestCode == UpLoadCarPicture.FROM_PICTURE_UP_LOADCARPACTURE) {//上传图片view
//            ((UpLoadCarPicture) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == AccidentSkeletonView.FROM_CAMERA_SKELETON || requestCode == AccidentSkeletonView.FROM_PICTURE_SKELETON || requestCode == AccidentSkeletonView.FROM_PIC_VIEWPAGER_SKELETON) {//结构件view
//            ((AccidentSkeletonView) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == ConditionPaintSurfaceView.FROM_CAMERA || requestCode == ConditionPaintSurfaceView.FROM_PICTURE || requestCode == ConditionPaintSurfaceView.FROM_PIC_VIEWPAGER) {
//            ((ConditionPaintSurfaceView) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == ConditionPaintThicknessView.FORM_PAINT) {
//            ((ConditionPaintThicknessView) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == ConditionPaintThicknessView.REQUEST_CONNECT_DEVICE) {
//            ((ConditionPaintThicknessView) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == ConditionGuiseView.FROM_CAMERA || requestCode == ConditionGuiseView.FROM_PICTURE || requestCode == ConditionGuiseView.FROM_PIC_VIEWPAGER) {
//            ((ConditionGuiseView) nowView).onActivityResultView(requestCode, resultCode, data);
//        } else if (requestCode == BaseInfoCarInfoView.REQUEST_CAR_BRAND || requestCode == BaseInfoCarInfoView.REQUEST_CAR_MODEL || requestCode == BaseInfoCarInfoView.REQUEST_CAR_SERIES
//                || requestCode == BaseInfoCarInfoView.REQUEST_CITY || requestCode == BaseInfoCarInfoView.REQUEST_PROVINCE || requestCode == BaseInfoCarInfoView.REQUEST_SCAN) {
//            ((BaseInfoCarInfoView) nowView).onActivityResultView(requestCode, resultCode, data);
//        }else if (requestCode == ConditionInteriorView.FROM_CAMERA || requestCode == ConditionInteriorView.FROM_PICTURE || requestCode == ConditionInteriorView.FROM_PIC_VIEWPAGER) {
//            ((ConditionInteriorView) nowView).onActivityResultView(requestCode, resultCode, data);
//        }
    }

    public void setTitle(String name) {

        ((TextView) (mTitleView.findViewById(R.id.tv_title_name))).setText(name);

    }

    public boolean saveNowSingleViewData() {
        ISave view = (ISave) nowView;
        return view.save();
    }

    /**
     * 快捷栏item点击事件
     */
    private QuickActionWidget.OnQuickActionClickListener mActionListener = new QuickActionWidget.OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {

            switch (position) {
                case 0://保存
                    commonSave();
                    break;
                case 1://下一项
                    commonSave();
                    showNextPage();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 2://提交

                    commonSave();


                    ContentValues values = new ContentValues();
                    values.put(DbHelper.KEY_DRAFT_BASE_INFO_STATUS, GlobalInfo.draft.base_info.getStatus());
                    values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, GlobalInfo.draft.condition.getStatus());

                    GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values);


                    // 如果未全部检测完成
                    if (!isAllChecksFinish()) {
                        mLeftLayoutAdapter.showIsOk(true);
                        return;
                    }

//                    if (dialog == null)
//                        dialog = new ProgressDialog(MainActivity.this);
//                    dialog.setTitle(R.string.publish);
//                    dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            if (upload != null)
//                                upload.cancel();
//                        }
//                    });
//
//                    dialog.setMessage("提交检测中，请稍候...");
//                    dialog.show();
//                    new Thread() {
//                        public void run() {
                    submit();
//                        }
//                    }.start();


                    break;
                case 3://保存并返回草稿页
                    if (saveNowSingleViewData()) {
                        ToastUtil.showToast(getTitleText() + "保存成功", true);
                        finish();
                    } else {
                        ToastUtil.showToast(getTitleText() + "保存失败", true);
                    }
                    break;

                case 4:
                    break;
            }
        }
    };

    private void commonSave() {
        if (saveNowSingleViewData()) {
            ToastUtil.showToast(getTitleText() + "保存成功", true);
        } else {
            ToastUtil.showToast(getTitleText() + "保存失败", true);
        }
    }

    private boolean isStart = false;

    /**
     * 数据提交
     */
    private void submit() {

        if (GlobalInfo.draft.upload_status == 1) {
            T.showShort(this, "已上传");
            return;
        }
        if (isStart) {
            ProgressDialogUtil.showProgressDlg(this, "上传车检报告……");
            return;
        }
        isStart = true;
        // 提交前，先上传图片。图片全部上传成功后，在回调接口中继续执行提交操作
        uploadPic();
    }

    /**
     * 上传图片
     */
    public void uploadPic() {
        ProgressDialogUtil.showProgressDlg(this, "上传车检报告……");
        startService(new Intent(UpCarPhotoService.ACT_UPLOAD_SERVICE));

//        upUtil = new UploadPicUtil(this);
//        ProgressDialogUtil.showProgressDlg(this, "提交车检图片");
//        upkeletonCover = false;
//        upPaintCover = false;
//        reqCount = 0;
//
//        uploadPaintCover();     // 上传漆膜厚度示意图
//        uploadkeletonCover();   // 上传事故勘察示意图
//        Draft draft = GlobalInfo.draft;
//        upload(draft.condition.paint_surface);  // 上传漆面检测
//        upload(draft.condition.guise);  // 外观检测
//        upload(draft.accident.skeletons);   // 结构件
//        upload(draft.photo);    // 车辆照片
    }

//    /**
//     * 上传漆膜厚度示意图
//     */
//    private void uploadPaintCover() {
//        ImageView iv = new ImageView(this);
//        boolean hasFix = CoverImageUtil.createPaintCoverView(GlobalInfo.draft.condition.paint_thickness, iv);
//        if (!hasFix) {
////            return;
//        }
//
//        iv.setDrawingCacheEnabled(true);
//        iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
//                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//        iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
//
//        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
//        try {
//            Util.saveBitmap2File(iv.getDrawingCache(), file);
//        } catch (IOException e) {
//            e.printStackTrace();
//            ToastUtil.showToastLong("保存漆膜检测示意图失败:" + e.getMessage());
//        }
//
//        String filePath = file.getAbsolutePath();
//        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
//            @Override
//            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
//                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
//                reqCount--;
//                upPaintCover = isSucceed;
//                if (isSucceed) {
//                    GlobalInfo.draft.condition.paintPicUrl = result;
//                    submitAfterUpPic();
//                } else {
//                    T.showShort(MainActivity.this, moduleName + ":" + result + "上传失败");
//                }
//            }
//        };
//        reqCount++;
//        upUtil.upSinglePic("漆膜厚度示意图", filePath, callback);
//    }
//
//    /**
//     * 上传漆膜检测示意图
//     */
//    private void uploadkeletonCover() {
//        Bitmap bitmap = CoverImageUtil.getSkeletonCoverBitmap(this, GlobalInfo.draft.accident.skeletons);
//        if (bitmap == null) {
//            return;
//        }
//        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
//        L.w("filePath = " + file.getAbsolutePath());
//        try {
//            Util.saveBitmap2File(bitmap, file);
//        } catch (IOException e) {
//            e.printStackTrace();
//            ToastUtil.showToastLong("保存漆膜检测示意图失败:" + e.getMessage());
//            return;
//        }
//
//        String filePath = file.getAbsolutePath();
//        UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
//            @Override
//            public void uploadCallback(boolean isSucceed, String result, String moduleName) {
//                System.out.println("isSucceed:" + isSucceed + ";result:" + result);
//                reqCount--;
//                upkeletonCover = isSucceed;
//                if (isSucceed) {
//                    GlobalInfo.draft.accident.skeletonPicUrl = result;
//                    submitAfterUpPic();
//                } else {
//                    T.showShort(MainActivity.this, moduleName + ":" + result + "上传失败");
//                }
//            }
//        };
//        reqCount++;
//        upUtil.upSinglePic("漆膜检测示意图", filePath, callback);
//    }
//
//    /**
//     * 上传图片
//     */
//    private void upload(final Photo[] photos) {
//        String filePath = null;
//
//        // 上传漆面检测图片
//        for (final Photo photo : photos) {
//            if (photo == null) {
//                L.i("photo==null");
//                continue;
//            }
//            filePath = photo.pic_path;
//
//            final String finalFilePath = filePath;
//            UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
//                @Override
//                public void uploadCallback(boolean isSucceed, String result, String moduleName) {
//                    System.out.println("isSucceed:" + isSucceed + ";result:" + result);
//                    reqCount--;
//                    if (isSucceed) {
//                        photo.pic_url = result;
//                        GlobalInfo.dbHelper.insertPhoto(finalFilePath, result);
//                        if (checkPhoto(photos))
//                            submitAfterUpPic();
//                    } else {
//                        T.showShort(MainActivity.this, moduleName + ":" + result + "上传失败");
//                    }
//                }
//            };
//            reqCount++;
//            upUtil.upSinglePic("车辆照片", filePath, callback);
//        }
//    }
//
//    private void upload(final Skeleton[] skeletons) {
//        String filePath = null;
//
//        for (final Skeleton skeleton : skeletons) {
//            if (skeleton == null) {
//                L.i("skeleton==null");
//                continue;
//            }
//            skeleton.pic_url_list.clear();
//            for (int i = 0; i < skeleton.pic_path_list.size(); i++) {
//                filePath = skeleton.pic_path_list.get(i);
//
//                final String finalFilePath = filePath;
//                UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
//                    @Override
//                    public void uploadCallback(boolean isSucceed, String result, String moduleName) {
//                        System.out.println("isSucceed:" + isSucceed + ";result:" + result);
//                        reqCount--;
//                        if (isSucceed) {
//                            skeleton.pic_url_list.add(result);
//                            GlobalInfo.dbHelper.insertPhoto(finalFilePath, result);
//                            if (checkSkeleton(skeletons))
//                                submitAfterUpPic();
//                        } else {
//                            T.showShort(MainActivity.this, moduleName + ":" + result + "上传失败");
//                        }
//                    }
//                };
//                reqCount++;
//                upUtil.upSinglePic("结构件图片", filePath, callback);
//            }
//        }
//    }
//
//    private void upload(final ResultIntArrayPics[] resultIntArrayPics) {
//        String filePath = null;
//
//        // 上传漆面检测图片
//        for (final ResultIntArrayPics arrayPic : resultIntArrayPics) {
//            if (arrayPic == null) {
//                L.i("arrayPic==null");
//                continue;
//            }
//
//            arrayPic.pic_url_list.clear();
//            for (int i = 0; i < arrayPic.pic_path_list.size(); i++) {
//                filePath = arrayPic.pic_path_list.get(i);
//
//                final String finalFilePath = filePath;
//                UploadPicUtil.UpSinglePicCallback callback = new UploadPicUtil.UpSinglePicCallback() {
//                    @Override
//                    public void uploadCallback(boolean isSucceed, String result, String moduleName) {
//                        System.out.println("isSucceed:" + isSucceed + ";result:" + result);
//                        reqCount--;
//                        if (isSucceed) {
//                            arrayPic.pic_url_list.add(result);
//                            GlobalInfo.dbHelper.insertPhoto(finalFilePath, result);
//                            if (checkResultIntArrayPics(resultIntArrayPics))
//                                submitAfterUpPic();
//                        } else {
//                            T.showShort(MainActivity.this, moduleName + ":" + result + "上传失败");
//                        }
//                    }
//                };
//                reqCount++;
//                upUtil.upSinglePic("综合检测照片", filePath, callback);
//            }
//        }
//    }
//
//    /**
//     * 判断车辆照片是否全部上传
//     */
//    public boolean checkPhoto(Photo[] photos) {
//        for (final Photo photo : photos) {
//            if (photo == null) {
//                L.i("photo==null");
//                continue;
//            }
//            if (TextUtils.isEmpty(photo.pic_url))
//                return false;
//        }
//        return true;
//    }
//
//    /**
//     * 判断结构件是否全部上传
//     */
//    public boolean checkSkeleton(Skeleton[] skeletons) {
//        for (final Skeleton item : skeletons) {
//            if (item == null) {
//                L.i("arrayPic==null");
//                continue;
//            }
//            if (item.pic_url_list == null || item.pic_url_list.size() != item.pic_path_list.size())
//                return false;
//        }
//        return true;
//    }
//
//    /**
//     * 判断漆面检测/外观检测是否全部上传
//     */
//    public boolean checkResultIntArrayPics(ResultIntArrayPics[] array) {
//        for (final ResultIntArrayPics arrayPic : array) {
//            if (arrayPic == null) {
//                L.i("arrayPic==null");
//                continue;
//            }
//            if (arrayPic.pic_url_list == null || arrayPic.pic_url_list.size() != arrayPic.pic_path_list.size())
//                return false;
//        }
//        return true;
//    }

    public void submitAfterUpPic() {
//        if (reqCount > 0)
//            return;

        ProgressDialogUtil.showProgressDlg(MainActivity.this, "提交验车结果");
        Draft draft = GlobalInfo.draft;
//        if (upPaintCover && upkeletonCover && checkResultIntArrayPics(draft.condition.paint_surface) &&
//                checkResultIntArrayPics(draft.condition.guise) && checkSkeleton(draft.accident.skeletons) && checkPhoto(draft.photo)) {
        // 图片全部上传完成，提交验车
        Map<String, String> params = new HashMap<String, String>();
        params.put("_token", AppInfoManager.getToken());
        params.put("_passport", UserInfoManager.getPASS_PORT());
        params.put("imei", GlobalInfo.IMEI);
        try {
            JSONObject json = new JSONObject(draft.toString());
            json.put("SysUserId", UserInfoManager.getUSER_ID());
            json.put("SysUserName", UserInfoManager.getUSERNAME());
            json.put("token", SUBMIT_ACCESS_TOKEN);
            params.put("data", json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Request req = new SubmitRequest(params, SUBMIT_URL,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        T.showShort(MainActivity.this, "上传成功");
                        updateDb();
                        isStart = false;
                        validateCarResult();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isStart = false;
                ProgressDialogUtil.dismissProgressDlg();
                T.showShort(MainActivity.this, "验车结果上传失败！");
            }
        });
        addQueue(req);
//        } else {
//            T.showShort(this, "图片上传失败，请重新提交");
//        }
    }

    /**
     * 更新状态是否已上传到车辆检测后台
     */
    private void updateDb() {
        if (check_result == 1) {
            GlobalInfo.draft.upload_status = 1;
            ContentValues values = new ContentValues();
            values.put(DbHelper.KEY_UPLOAD_STATUS, GlobalInfo.draft.upload_status);
            // 保存成功
            GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values);
        } else {// TODO 不通过的车辆检测数据直接删除
            GlobalInfo.dbHelper.deleteDraf(GlobalInfo.draft.car_plate);
        }
    }

    /**
     * 当前车辆检测结果 // 1 通过  2 不通过
     */
    private int check_result = 1;

    /**
     * 提交验车结果
     */
    public void validateCarResult() {
        Draft draft = GlobalInfo.draft;
        check_result = 1;

        if (hasFireOrWater(draft) || isSkeletonError(draft) || isCoverError(draft) > 5
                || isPaintThickness(draft))
            check_result = 2;

        Map<String, String> params = new HashMap<String, String>();
        params.put("id", draft.info_number);
        params.put("check_result", check_result + "");     // 1 通过  2 不通过
        params.put("title", draft.base_info.use_info.brand_str + " " + draft.base_info.use_info.series_str + " " + draft.base_info.use_info.model_str);     // 1 通过  2 不通过
        params.put("check_id", draft.base_info.car_type_info.getCheckid());
        params.put("no_check_reason", "");
        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.CHECK_CAR_RESULT, params,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(MainActivity.this, "提交验车结果成功");
//                        GlobalInfo.dbHelper.deleteDraf(GlobalInfo.draft.car_plate);
//                        GlobalInfo.draft = null;

                        if (check_result == 2)
                            new AlertDialog.Builder(MainActivity.this).setMessage("车辆检测结果不通过")
                                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            finish();
                                        }
                                    })
                                    .show();
                        else {
                            finish();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProgressDialogUtil.dismissProgressDlg();
                        T.showShort(MainActivity.this, error.getMessage());
                    }
                });
        ProgressDialogUtil.showProgressDlg(this, "提交验车结果");
        addQueue(req);
    }
    /**
     * 是否有超过5处（不包括5）有修复痕迹
     *
     * @param draft
     * @return true 有问题 false没有问题
     * */
    private boolean isPaintThickness(Draft draft) {
        int count = 0;
        for (PaintThickness paintThickness : draft.condition.paint_thickness) {
            if (paintThickness.max > 1500) {//如果是喷漆有修复
                count++;
                if(count > 5){//超过5处则直接返回
                    break;
                }
            }
        }
        return (count > 5);
    }

    /**
     * 是否有泡水火烧
     *
     * @param draft
     * @return true 有问题  false 没问题
     */
    private boolean hasFireOrWater(Draft draft) {
        for (ResultBoolean result : draft.fire) {
            if (result.result) {
                return true;
            }
        }

        for (ResultBoolean result : draft.dip) {
            if (result.result) {
                return true;
            }
        }

        return false;
    }

    /**
     * 结构件是否OK
     *
     * @param draft
     * @return true 有问题  false 没问题
     */
    private boolean isSkeletonError(Draft draft) {
        for (Skeleton result : draft.accident.skeletons) {
            if (result == null)
                continue;

            if (result.result != 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * 覆盖件有问题的地方是否超过5个
     *
     * @param draft
     * @return
     */
    private int isCoverError(Draft draft) {
        int num = 0;

        for (ResultInt result : draft.accident.cover) {
            if (result == null)
                continue;

            if (result.result != 0) {
                num += 1;
            }

//            if (num>5){
//                return num;
//            }
        }

        for (ResultInt result : draft.accident.reinforcement) {
            if (result == null)
                continue;

            if (result.result != 0) {
                num += 1;
            }
//            if (num>5){
//                return num;
//            }
        }

        return num;
    }

    /**
     * 是否所有检测都已完成
     *
     * @return
     */
    private boolean isAllChecksFinish() {

        Draft draft = GlobalInfo.draft;

        for (int i = 0; i < draft.status.length; i++) {
            if (draft.status[i] != Draft.STATUE_FINISH) {
                switch (i) {
                    case 0:
                        ToastUtil.showToastLong("【基础信息】尚未完成");
                        break;
                    case 1:
                        ToastUtil.showToastLong("【综合检测】尚未完成");
                        break;
                    case 2:
                        ToastUtil.showToastLong("【事故勘察】尚未完成");
                        break;
                    case 3:
                        ToastUtil.showToastLong("【上传照片】-【行驶证】尚未选择");
                        break;
                    case 4:
                        ToastUtil.showToastLong("【浸泡检测】尚未完成");
                        break;
                    case 5:
                        ToastUtil.showToastLong("【失火检测】尚未完成");
                        break;
                }

                return false;
            }
        }

        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(UpCarPhotoService.ACT_UPLOAD_SERVICE));
        unregisterReceiver(mReceiver);
    }

    public class MyReceiver extends BroadcastReceiver {
        public static final String ACT_MAIN_RECEIVER = "com.uchedao.vehicledetection.activity.MainActivity.MyReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            int failedCount = intent.getIntExtra("failedCount", 0);
            if (failedCount > 0) {
                isStart = false;
                String failedCount_str = String.format("%d", failedCount);
                int succeedCount = intent.getIntExtra("succeedCount", 0);
                new AlertDialog.Builder(MainActivity.this).setTitle("提交验车")
                        .setMessage(getString(R.string.up_pic_toast, succeedCount+"", failedCount+""))
                        .setPositiveButton(getString(R.string.btn_reupload), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                submit();
                            }
                        })
                        .setNegativeButton(getString(R.string.btn_goon_upload), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
//                                submitAfterUpPic();
                            }
                        })
                        .show();
            } else {
                submitAfterUpPic();
            }
        }
    }

    @Override
    public void onBackPressed() {
        //保存至草稿
        saveNowSingleViewData();
        finish();
    }
}
